<template>
  <view class="container">
    <!-- 收货地址 -->
    <view class="address-section" @click="selectAddress">
      <view class="address-content" v-if="address && address.id">
        <view class="address-info">
          <view class="address-user-line">
            <text class="user-name">{{ address.name }}</text>
            <text class="user-phone">{{ address.tel }}</text>
            <text class="address-region">{{ address.address }}</text>
          </view>
          <view class="address-detail-line">
            <text class="address-detail">{{ address.desc }}</text>
          </view>
        </view>
        <uni-icons type="right" size="16" color="#ccc"></uni-icons>
      </view>
      <view class="address-content" v-else>
        <view class="no-address">
          <uni-icons type="location-filled" size="16" color="#ccc"></uni-icons>
          <text class="no-address-text">暂无地址</text>
        </view>
        <uni-icons type="right" size="16" color="#ccc"></uni-icons>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="product-section">
      <view class="product-info">
        <image
          :src="product.images[0]"
          class="product-image"
          mode="aspectFill"
        ></image>
        <view class="product-details">
          <text class="product-title">{{ product.title }}</text>
          <text class="product-spec" v-if="product.spec"
            >{{ product.spec }}</text
          >
          <view class="product-price-quantity">
            <text class="product-price">¥{{ product.price }}</text>
            <!-- 将数量显示替换为步进器 -->
            <view class="stepper">
              <view class="stepper-button" @click="decreaseQuantity">-</view>
              <input
                class="stepper-input"
                v-model="quantity"
                type="number"
                @blur="onQuantityChange"
              />
              <view class="stepper-button" @click="increaseQuantity">+</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单金额 -->
    <view class="order-summary">
      <view class="summary-item">
        <text class="summary-label">商品金额</text>
        <text class="summary-value">¥{{ totalAmount }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">运费</text>
        <text class="summary-value">¥{{ shippingFee }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">优惠券抵扣</text>
        <text class="summary-value">无可用</text>
      </view>
      <view class="divider"></view>
      <!-- 添加的总价显示 -->
      <view class="summary-item total-row">
        <text class="summary-label">总价</text>
        <text class="summary-value total-amount">¥{{ finalAmount }}</text>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <view class="bottom-nav">
      <view class="total-price">
        <text class="price-label">总价:</text>
        <text class="price-amount">¥{{ finalAmount }}</text>
      </view>
      <view class="buy-button" @click="submitOrder">
        <text class="buy-text">立即购买</text>
      </view>
    </view>
  </view>
</template>

<script>
import uniIcons from "@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue";
import { addressApi, orderApi } from '@/api/indexAPI.js';
// 引入全局配置
import { public_api } from '@/static/public.js';

export default {
  components: {
    uniIcons,
  },
  data() {
    return {
      quantity: 1,
      product: {
        id: "",
        title: "",
        price: "0.00",
        spec: "",
        images: [],
      },
      shippingFee: "0.00",
      address: {},
      // 添加全局API地址
      baseUrl: public_api
    };
  },
  computed: {
    totalAmount() {
      return (parseFloat(this.product.price) * this.quantity).toFixed(2);
    },
    finalAmount() {
      return (
        parseFloat(this.totalAmount) + parseFloat(this.shippingFee)
      ).toFixed(2);
    },
  },
  onLoad(options) {
    // 接收来自商品详情页的参数
    if (options && options.productInfo) {
      try {
        const productInfo = JSON.parse(decodeURIComponent(options.productInfo));
        this.product = {
          id: productInfo.id || "",
          title: productInfo.title || "",
          price: productInfo.price || "0.00",
          spec: productInfo.spec || "",
          images: productInfo.images || [],
        };
        this.quantity = parseInt(options.quantity) || 1;
      } catch (e) {
        console.error("解析商品信息失败", e);
      }
    }

    // 获取收货地址信息
    this.getAddress();
  },
  onShow() {
    // 页面显示时重新获取地址信息
    this.getAddress();
    
    // 页面显示时检查是否有选中的地址
    const selectedAddress = uni.getStorageSync('selectedAddress');
    if (selectedAddress) {
      this.address = selectedAddress;
      uni.removeStorageSync('selectedAddress');
    }
    
    // 检查是否有地址更新标记
    const addressUpdated = uni.getStorageSync('addressUpdated');
    if (addressUpdated) {
      this.getAddress();
      uni.removeStorageSync('addressUpdated');
    }
  },
  methods: {
    getAddress() {
      const token = uni.getStorageSync("token") || "";
      const userId = uni.getStorageSync("userId") || "";

      uni.request({
        url: this.baseUrl + "/api/address",
        method: "POST",
        header: {
          "Content-Type": "application/json",
          token: token,
          id: userId,
        },
        data: {
          uid: userId,
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 1) {
            // 查找默认地址 (default = 1)
            const addresses = res.data.data || [];
            const defaultAddress = addresses.find(
              (addr) => addr.default === "1"
            );
            if (defaultAddress) {
              this.address = defaultAddress;
            } else if (addresses.length > 0) {
              // 如果没有设置默认地址，则使用第一个地址
              this.address = addresses[0];
            }
          } else {
            console.error("获取地址失败:", res);
          }
        },
        fail: (err) => {
          console.error("请求地址接口失败:", err);
        },
      });
    },
    selectAddress() {
      // 跳转到收货地址页面
      uni.navigateTo({
        url: "/pages/location/location?selectMode=true",
      });
    },

    submitOrder() {
      // 检查是否选择了收货地址
      if (!this.address || !this.address.id) {
        uni.showToast({
          title: "请先选择收货地址",
          icon: "none",
        });
        return;
      }

      // 构造规格参数 - 保持原来的格式，但规格名称固定为"name"
      let norm = [];
      
      // 处理从商品详情页传递过来的规格信息
      if (this.product.spec && this.product.spec !== "默认") {
        // 如果规格信息存在且不是默认值
        if (this.product.spec.includes(":")) {
          // 如果是 "规格名:规格值" 格式，提取规格值，规格名称固定为"name"
          const specs = this.product.spec.split(" ");
          norm = specs.map(spec => {
            const parts = spec.split(":");
            return {
              name: "name",  // 固定为"name"
              value: parts[1] || parts[0] || ''  // 使用规格值
            };
          }).filter(item => item.value);
        } else {
          // 如果是简单规格值，使用固定名称"name"
          norm = [{
            name: "name",  // 固定为"name"
            value: this.product.spec
          }];
        }
      } else {
        // 如果没有规格信息或为默认规格
        norm = [{
          name: "name",  // 固定为"name"
          value: "默认"
        }];
      }

      // 构造请求参数
      const params = {
        user_id: uni.getStorageSync("userId") || "",
        address_id: this.address.id,
        goods_id: this.product.id,
        num: this.quantity.toString(),
        norm: JSON.stringify(norm),
        money: this.finalAmount
      };

      console.log("提交订单参数:", params);

      // 显示加载提示
      uni.showLoading({
        title: "提交订单中..."
      });

      // 调用支付接口
      uni.request({
        url: this.baseUrl + "/api/order/pay",
        method: "POST",
        header: {
          "Content-Type": "application/json"
        },
        data: params,
        success: (res) => {
          console.log("支付接口请求成功，返回数据:", res);
          
          // 尝试从返回的数据中提取有效的JSON
          let jsonData = null;
          if (typeof res.data === 'string') {
            // 尝试从字符串中提取JSON部分
            const jsonStart = res.data.indexOf('{"code"');
            if (jsonStart !== -1) {
              const jsonString = res.data.substring(jsonStart);
              try {
                jsonData = JSON.parse(jsonString);
              } catch (e) {
                console.error("解析JSON数据失败:", e);
              }
            }
          } else if (typeof res.data === 'object') {
            jsonData = res.data;
          }
          
          // 棣查解析后的数据
          if (jsonData && jsonData.code === 1) {
            // 支付成功，跳转到支付成功页面
            uni.redirectTo({
              url: "/pages/paysuccess/paysuccess?orderInfo=" + encodeURIComponent(JSON.stringify({
                orderNo: jsonData.data.orderNo || '未知订单号',
                amount: this.finalAmount,
                payTime: new Date().toLocaleString()
              }))
            });
          } else {
            uni.showToast({
              title: (jsonData && jsonData.msg) || res.data.msg || "支付失败",
              icon: "none"
            });
          }
        },
        fail: (err) => {
          console.log("支付接口请求失败:", err);
          uni.showToast({
            title: "网络请求失败",
            icon: "none"
          });
          console.error("支付请求失败:", err);
        },
        complete: () => {
          console.log("支付接口请求完成");
          uni.hideLoading();
        }
      });
    },


    // 增加步进器相关方法
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },
    increaseQuantity() {
      this.quantity++;
    },
    onQuantityChange(e) {
      let value = parseInt(e.target.value);
      if (isNaN(value) || value < 1) {
        value = 1;
      }
      this.quantity = value;
    },
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

.order-header {
  background-color: #fff;
  padding: 30rpx;
  text-align: center;
  border-bottom: 1rpx solid #eee;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.address-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 10rpx;
  padding: 30rpx;
}

.address-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.address-info {
  flex: 1;
  margin-right: 20rpx;
}

.address-user-line {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.user-name {
  font-size: 28rpx;
  margin-right: 20rpx;
}

.user-phone {
  font-size: 28rpx;
  color: #666;
  margin-right: 20rpx;
}

.address-region {
  font-size: 28rpx;
  color: #666;
  width: 45%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.address-detail-line {
  display: flex;
  align-items: center;
}

.address-detail {
  font-size: 26rpx;
  color: #999;
}

.no-address {
  flex: 1;
  display: flex;
  align-items: center;
}

.no-address-text {
  margin-left: 10rpx;
  color: #999;
}

.product-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 10rpx;
  padding: 20rpx;
}

.product-info {
  display: flex;
  margin-top: 20rpx;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
}

.product-details {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-title {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
}

.product-spec {
  font-size: 24rpx;
  color: #999;
}

.product-price-quantity {
  display: flex;
  justify-content: space-between;
}

.product-price {
  font-size: 32rpx;
  color: #ff0000;
  font-weight: bold;
}

.product-quantity {
  font-size: 28rpx;
  color: #666;
}

/* 步进器样式 */
.stepper {
  display: flex;
  flex-direction: row;
  align-items: center;
  border-radius: 5rpx;
  width: 180rpx;
  height: 50rpx;
}

.stepper-button {
  width: 50rpx;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  border: 1rpx solid #ccc;
}

.stepper-input {
  flex: 1;
  height: 100%;
  text-align: center;
  font-size: 28rpx;
  color: #333;
}

.stepper-button:active {
  background-color: #e0e0e0;
}

.order-summary {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 10rpx;
  padding: 20rpx;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
}

.summary-label {
  font-size: 28rpx;
  color: #666;
}

.summary-value {
  font-size: 28rpx;
  color: #333;
}

.total-row {
  display: flex;
  width: 100%;
  justify-content: flex-end;
}

/* 底部导航栏 */
.bottom-nav {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  border-top: 1rpx solid #eee;
}

.total-price {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 20rpx;
  margin-left: 14px;
}

.price-label {
  font-size: 28rpx;
  color: #333;
}

.price-amount {
  font-size: 28rpx;
  color: #666;
  margin-left: 10rpx;
}

.buy-button {
  width: 200rpx;
  height: 60rpx;
  background-color: #ff0000;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 25px;
  margin-right: 20rpx;
}

.buy-text {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
}

/* 分割线 */
.divider {
  height: 2rpx;
  background-color: #cccccc;
  margin: 20rpx 0;
}
</style>
